from django.contrib.auth.hashers import make_password, check_password
from rest_framework.decorators import api_view
from .models import users
from utils.response import ApiResponse
import time
from django.middleware.csrf import get_token

@api_view(['GET'])
def get_user_list(request):
    user_list = users.objects.all().values(
        'id', 'username', 'avatar', 'mobile', 'status','role', 'create_time', 'update_time'
        )
    #create_time 转为datetime格式
    for user in user_list:
        user['create_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(user['create_time']))
        user['update_time'] = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(user['update_time']))
    return ApiResponse(data=list(user_list))
@api_view(['GET'])
def get_simple_user_list(request):
    try: 
        user_list = users.objects.all().order_by('-id').values('id', 'username')
        return ApiResponse(data=list(user_list))
    except Exception as e:
        return ApiResponse(code=500, message=str(e))
    

@api_view(['POST'])
def register(request):
    try:
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        role = request.data.get('role', 'user')
        status = request.data.get('status', 1)
        
        if not all([username, password, mobile]):
            return ApiResponse(code=400, message='参数不完整')
        
        # 增加密码长度验证
        if len(password) < 8:
            return ApiResponse(code=400, message='密码长度至少需要8位')
            
        if users.objects.filter(username=username).exists():
            return ApiResponse(code=400, message='用户名已存在')
            
        if users.objects.filter(mobile=mobile).exists():
            return ApiResponse(code=400, message='手机号已注册')
            
        new_users = users(
            username=username,
            password=make_password(password),
            mobile=mobile,
            role=role,
            create_time=int(time.time()),
            update_time=int(time.time()),
            reg_ip=request.META.get('REMOTE_ADDR', ''),
            last_login_ip=request.META.get('REMOTE_ADDR', ''),
            status=status
        )
        
        new_users.save()
        
        return ApiResponse(message='注册成功')
    except Exception as e:
        return ApiResponse(code=500, message=str(e))

@api_view(['POST'])
def user_login(request):
    try:
        username_or_mobile = request.data.get('username')  # 建议改为 username_or_mobile 保持参数名一致
        password = request.data.get('password')
        
        if not all([username_or_mobile, password]):
            return ApiResponse(code=400, message='用户名/手机号和密码不能为空')

        # 先尝试用户名登录 - 使用加密后的密码验证
        user_obj = users.objects.filter(username=username_or_mobile).first()
        
        if user_obj is None:
            user_obj = users.objects.filter(mobile=username_or_mobile).first()
    
        if user_obj and check_password(password,user_obj.password):
            user_obj.last_login_ip = request.META.get('REMOTE_ADDR', '')
            user_obj.update_time = int(time.time())
            user_obj.save()
            
            return ApiResponse(message='登录成功', data={
                'token': get_token(request),
                'user_info': {
                    'id': user_obj.id,
                    'username': user_obj.username,
                    'avatar': user_obj.avatar,
                    'mobile': user_obj.mobile,
                    'status': user_obj.status,
                    'role': user_obj.role,
                    'create_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(user_obj.create_time)),
                    'update_time': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(user_obj.update_time))
                }
            })

        # 优化错误提示逻辑
        if users.objects.filter(username=username_or_mobile).exists() or \
           users.objects.filter(mobile=username_or_mobile).exists():
            return ApiResponse(code=400, message='密码错误')
        else:
            return ApiResponse(code=400, message='用户名/手机号不存在')
    except Exception as e:
        return ApiResponse(code=500, message=str(e))

@api_view(['POST'])
def reset_password(request):
    try:
        mobile = request.data.get('mobile')
        new_password = request.data.get('new_password')
        
        if not all([mobile, new_password]):
            return ApiResponse(code=400, message='参数不完整')
            
        user_obj = users.objects.filter(mobile=mobile).first()
        
        if not user_obj:
            return ApiResponse(code=400, message='用户不存在')
            
        user_obj.password = make_password(new_password)
        user_obj.update_time = int(time.time())
        user_obj.save()
        
        return ApiResponse(message='密码重置成功')
    except Exception as e:
        return ApiResponse(code=500, message=str(e))
#更新用户信息，可能是更新密码，手机号，角色，状态
@api_view(['PUT'])
def update_user(request):
    try:
        id = request.data.get('id')
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        role = request.data.get('role')
        status = request.data.get('status')
        if not id:
            return ApiResponse(code=400, message='用户ID不能为空')
            
        if not any([username, password, mobile, role, status is not None]):
            return ApiResponse(code=400, message='至少需要提供一个修改参数')

        user_obj = users.objects.filter(id=id).first()
        if not user_obj:
            return ApiResponse(code=400, message='用户不存在')
            
        # 检查手机号是否已被其他用户使用
        if mobile and users.objects.filter(mobile=mobile).exclude(id=id).exists():
            return ApiResponse(code=400, message='手机号已被其他用户使用')
            
        if username: user_obj.username = username
        if password: user_obj.password = make_password(password)
        if mobile: user_obj.mobile = mobile
        if role: user_obj.role = role
        if status is not None: user_obj.status = status
        user_obj.update_time = int(time.time())
        user_obj.save()
        
        return ApiResponse(message='用户信息更新成功')
    except Exception as e:
        return ApiResponse(code=500, message=str(e))

@api_view(['DELETE'])
def delete_user(request,user_id):
    try:
        if not user_id:
            return ApiResponse(code=400, message='用户ID不能为空')
            
        user_obj = users.objects.filter(id=user_id).first()
        if not user_obj:
            return ApiResponse(code=400, message='用户不存在')
            
        user_obj.delete()
        return ApiResponse(message='用户删除成功')
    except Exception as e:
        return ApiResponse(code=500, message=str(e))

